package com.kfzx.www.emptyviewdemo;

import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class AdapterDataObserverActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private SwipeRefreshLayout mRefreshLayout;
    private EmptyRecyclerView mRecyclerView;
    private List<String> mStringList = new ArrayList<>();
    private StringAdapter mAdapter;
    private View mEmptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adapter_data_observer);

        initViews();
    }

    private void initViews() {
        mEmptyView = LayoutInflater.from(this).inflate(R.layout.empty_view_layout, null);
//        mEmptyView = (View) findViewById(R.id.image_view);
        mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        mRefreshLayout.setOnRefreshListener(this);
        mRecyclerView = (EmptyRecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        initStringList();
        mAdapter = new StringAdapter(this, mStringList);

        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setEmptyView(mEmptyView);
    }

    private void initStringList() {
        for (int i = 0; i < 30; i++) {
            mStringList.add("hello world" + i);
        }
    }

    @Override
    public void onRefresh() {
        mRefreshLayout.setRefreshing(true);
        Message message = Message.obtain();
        message.what = 1;
        mHandler.sendMessageDelayed(message, 2000);

    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mRefreshLayout.setRefreshing(false);
                    if (mStringList.size() > 0) {
                        mStringList.clear();
                        mAdapter.notifyDataSetChanged();
                    } else {
                        initStringList();
                        mAdapter.notifyDataSetChanged();
                    }
                    break;
                default:
                    break;
            }
        }
    };
}
